//
//  LongitudeAndLatitude.m
//  WildDonkey
//
//  Created by 孙俊 on 15/3/30.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "LongitudeAndLatitude.h"

@interface LongitudeAndLatitude ()
{
	CLLocationManager *locationManager;//本地的地理位置信息
	CLGeocoder *geocoder;//坐标转换为地址
	CLPlacemark *placemark;//地址标记
}

@end


@implementation LongitudeAndLatitude

- (void)dealloc
{
	[_address release];
	[_lng release];
	[_lat release];
	[locationManager release];
	[geocoder release];
	[placemark release];
	[super dealloc];
}


#pragma mark - gps


- (void)beginLBS

{
	
	locationManager = [[CLLocationManager alloc] init]; //初始化本地位置的类实例
	geocoder = [[CLGeocoder alloc] init]; //打开经纬度与地理位置的转换
	locationManager.delegate = self; //设置委托
	locationManager.desiredAccuracy = kCLLocationAccuracyBest; //设置精确度最好
	
	[locationManager startUpdatingLocation];//更新
	
	NSLog(@"%@",_lat);
	NSLog(@"%@",_lng);
	
}

//出现错误的时候
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	NSLog(@"didFailWithError: %@", error);
	
	if(error.code == kCLErrorLocationUnknown){
		NSLog(@"当前无法获取到位置信息。");
	} else if (error.code == kCLErrorNetwork) {
		NSLog(@"网络异常 - 无法获取到位置信息。");
	} else if (error.code == kCLErrorDenied) {
		NSLog(@"您的移动设备禁用了获取位置的服务。");
		[locationManager stopUpdatingLocation];
	}
	UIAlertView *errorAlert = [[UIAlertView alloc]
							   initWithTitle:@"错误提醒"
							   message:@"获取位置信息失败！"
							   delegate:nil
							   cancelButtonTitle:@"OK"
							   otherButtonTitles:nil];
	[errorAlert show];
}

//更新位置，以及经纬度数据与详细地理位置进行转换
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	NSLog(@"didUpdateToLocation: %@", newLocation);
	CLLocation *currentLocation = newLocation;
	
	if(currentLocation != nil){
		_lat = [NSString stringWithFormat:@"%.11f", currentLocation.coordinate.latitude];
		_lng = [NSString stringWithFormat:@"%.11f", currentLocation.coordinate.longitude];
		
		
		
	}
	
	// 停止location manager
	[locationManager stopUpdatingLocation];
	
	// 转换地址
	
	[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
		
		if(error == nil && [placemarks count]>0){
			placemark = [placemarks lastObject];
			_address = [NSString stringWithFormat:@"%@ %@\n%@\n%@",
						placemark.country,
						placemark.locality,
						placemark.subLocality,
						placemark.description];
			NSLog(@"%@",_address);
			
			
		} else {
			_address = @"地址没有找到！";
		}
	}];
}

@end
